package com.tangkun.environment.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.bumptech.glide.Glide;
import com.tangkun.environment.R;
import com.tangkun.environment.application.Session;
import com.tangkun.environment.entity.login.DepartmentscopeIndexReturn;
import com.tangkun.environment.fragment.main.Main1Fragment;
import com.tangkun.environment.fragment.main.Main2Fragment;
import com.tangkun.environment.fragment.main.Main3Fragment;
import com.tangkun.environment.network.GlobalUrl;
import com.tangkun.environment.network.MySubscribe;
import com.tangkun.environment.rx.RxActivityHelper;
import com.tangkun.environment.utils.GlideCacheUtil;
import com.tangkun.environment.utils.JumpHelper;
import com.tangkun.environment.utils.LogUtils;
import com.tangkun.environment.utils.SharePrefercesUtils;
import com.tangkun.environment.view.CircleImageView;
import com.tangkun.environment.view.CommonDialog;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.CropCircleTransformation;


/**
 * 主页面
 */
public class MainActivity extends BaseActivity {
    @BindView(R.id.tv_drawer_qiyeguanli_weiguanlian)
    TextView tvDrawerQiyeguanliWeiguanlian;
    @BindView(R.id.ll_drawer_qiyeguanli)
    LinearLayout llDrawerQiyeguanli;
    @BindView(R.id.ll_drawer_xitongtongzhi)
    LinearLayout llDrawerXitongtongzhi;
    @BindView(R.id.ll_drawer_xinxiaoxishezhi)
    LinearLayout llDrawerXinxiaoxishezhi;
    @BindView(R.id.ll_drawer_qingkonghuancun)
    LinearLayout llDrawerQingkonghuancun;
    @BindView(R.id.ll_drawer_guanyuyubangzhu)
    LinearLayout llDrawerGuanyuyubangzhu;
    //Frament初始化
    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;
    private Main1Fragment main1Fragment;
    private Main2Fragment main2Fragment;
    private Main3Fragment main3Fragment;

    @BindView(R.id.ll_main)
    LinearLayout llMain;
    @BindView(R.id.civ_drawer_photo)
    CircleImageView civDrawerPhoto;
    @BindView(R.id.tv_drawer_name)
    TextView tvDrawerName;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.fl_main_container)
    FrameLayout flMainContainer;
    @BindView(R.id.rb_main1)
    RadioButton rbMain1;
    @BindView(R.id.rb_main2)
    RadioButton rbMain2;
    @BindView(R.id.rb_main3)
    RadioButton rbMain3;
    @BindView(R.id.rg_main)
    RadioGroup rgMain;
    @BindView(R.id.tv_main3_unread_num)
    TextView tvMain3UnreadNum;//在线会诊未读数量
    @BindView(R.id.tv_main4_unread_num)
    TextView tvMain4UnreadNum;//消息管理／在线随访未读数量

    private Context mContext;

    private SDKReceiver mReceiver;
    private static final String LTAG = MainActivity.class.getSimpleName();

    /**
     * 定位监听监听
     */
    public MyLocationListenner myListener = new MyLocationListenner();
    /**
     * 定位相关
     */
    LocationClient mLocClient;
    /**
     * 纬度
     */
    private double mCurrentLat = 0.0;
    /**
     * 经度
     */
    private double mCurrentLon = 0.0;

    /**
     * 构造广播监听类，监听 SDK key 验证以及网络异常广播
     */
    public class SDKReceiver extends BroadcastReceiver {

        public void onReceive(Context context, Intent intent) {
            String s = intent.getAction();
            Log.d(LTAG, "action: " + s);
            if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)) {
                LogUtils.e("key 验证出错! 错误码 :" + intent.getIntExtra
                        (SDKInitializer.SDK_BROADTCAST_INTENT_EXTRA_INFO_KEY_ERROR_CODE, 0)
                        + " ; 请在 AndroidManifest.xml 文件中检查 key 设置");
            } else if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK)) {
                LogUtils.e("key 验证成功! 功能可以正常使用");
            } else if (s.equals(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR)) {
                LogUtils.e("网络出错");
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initView();
        initListener();
        initData();
        refreshFragment();
        initLoacation();
        departmentscopeIndex();

//        // 注册 SDK 广播监听者
//        IntentFilter iFilter = new IntentFilter();
//        iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK);
//        iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
//        iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);
//        mReceiver = new SDKReceiver();
//        registerReceiver(mReceiver, iFilter);
    }


    /**
     * 获取定位
     */
    private void initLoacation() {
        // 定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setIsNeedAddress(true);//需要请求地址吗
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(60 * 1000);//定位间隔 毫秒
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null) {
                return;
            }
            //纬度
            mCurrentLat = location.getLatitude();
            //经度
            mCurrentLon = location.getLongitude();
            LogUtils.e("mCurrentLat:" + mCurrentLat + "    mCurrentLon:" + mCurrentLon + "  city" + location.getCity());
            //保存纬度
            SharePrefercesUtils.setLatitude(MainActivity.this, mCurrentLat + "");
            //保存经度
            SharePrefercesUtils.setLongitude(MainActivity.this, mCurrentLon + "");
        }

        public void onReceivePoi(BDLocation poiLocation) {

        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        refreshFragment();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        //初始化Fragment
        fragmentManager = getSupportFragmentManager();
        main1Fragment = new Main1Fragment();
        main2Fragment = new Main2Fragment();
        main3Fragment = new Main3Fragment();
    }

    /**
     * 初始化监听事件
     */
    private void initListener() {
        //底部3个按钮监听事件
        rgMain.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                hideAllFragment();
                switch (checkedId) {
                    case R.id.rb_main1:
                        if (!main1Fragment.isAdded())
                            fragmentTransaction.add(R.id.fl_main_container, main1Fragment);
                        fragmentTransaction.show(main1Fragment);
                        break;
                    case R.id.rb_main2:
                        if (!main2Fragment.isAdded())
                            fragmentTransaction.add(R.id.fl_main_container, main2Fragment);
                        fragmentTransaction.show(main2Fragment);
                        break;
                    case R.id.rb_main3:
                        if (!main3Fragment.isAdded())
                            fragmentTransaction.add(R.id.fl_main_container, main3Fragment);
                        fragmentTransaction.show(main3Fragment);
                        break;
                }
                fragmentTransaction.commitAllowingStateLoss();
            }
        });
        rbMain1.setChecked(true);
    }

    /**
     * 隐藏所有Fragment
     */
    private void hideAllFragment() {
        fragmentTransaction = fragmentManager.beginTransaction();
        if (main1Fragment.isVisible())
            fragmentTransaction.hide(main1Fragment);
        if (main2Fragment.isVisible())
            fragmentTransaction.hide(main2Fragment);
        if (main3Fragment.isVisible())
            fragmentTransaction.hide(main3Fragment);
    }

    private void initData() {
        //左抽屉头像
        Glide.with(MainActivity.this)
                .load(GlobalUrl.IMG_URL + Session.getInstance().getUserHeadPicture())
                .bitmapTransform(new CropCircleTransformation(MainActivity.this))
                .placeholder(R.mipmap.ic_wrong_head)
                .dontAnimate()
                .into(civDrawerPhoto);
        //已登录
        if (SharePrefercesUtils.getLoginStatus(MainActivity.this)) {
            //姓名
            tvDrawerName.setText(Session.getInstance().getUserNickName() + "");
            //绑定企业数量
            if (Session.getInstance().getUserBindlist() != null && Session.getInstance().getUserBindlist().size() > 0) {
                tvDrawerQiyeguanliWeiguanlian.setText(Session.getInstance().getUserBindlist().size() + "个");
            } else {
                tvDrawerQiyeguanliWeiguanlian.setText("未关联");
            }
        } else {//未登录
            // 姓名
            tvDrawerName.setText("暂未登录");
            //绑定企业
            tvDrawerQiyeguanliWeiguanlian.setText("");
        }
    }

    /**
     * 发出通知刷新Fragment
     */
    private void refreshFragment() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                EventBus.getDefault().post(true, "MainActivity.refreshFragment");
            }
        }, 100);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    /**
     * 在线会诊未读数
     */
    private int unReadNumZaixianhuizhen = 0;

    /**
     * 未读数 在线会诊]
     */
    private void initUnReadNumZaixianhuizhen() {
        //在线会诊
        if (unReadNumZaixianhuizhen > 0) {
            tvMain3UnreadNum.setText(unReadNumZaixianhuizhen + "");
            tvMain3UnreadNum.setVisibility(View.VISIBLE);
        } else {
            tvMain3UnreadNum.setText(unReadNumZaixianhuizhen + "");
            tvMain3UnreadNum.setVisibility(View.GONE);
        }
    }

    /**
     * 返回键先关闭侧滑菜单
     */
    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawers();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        Session.getInstance().destroy();
    }

    /**
     * 点击左抽屉控件监听
     *
     * @param view
     */
    public void nothing(View view) {

    }

    /**
     * 关左抽屉
     *
     * @param view
     */
    public void closeDrawer(View view) {
        drawerLayout.closeDrawers();
    }


    @Subscriber(tag = "MainActivity.openDrawer")
    /**
     * 接收到通知打开左抽屉
     * @param flag
     */
    private void openDrawer(boolean flag) {
        drawerLayout.openDrawer(GravityCompat.START);
    }

    @OnClick({R.id.civ_drawer_photo, R.id.ll_drawer_qiyeguanli, R.id.ll_drawer_xitongtongzhi, R.id.ll_drawer_xinxiaoxishezhi, R.id.ll_drawer_qingkonghuancun, R.id.ll_drawer_guanyuyubangzhu})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.civ_drawer_photo://头像
                drawerLayout.closeDrawers();
                if (SharePrefercesUtils.getLoginStatus(MainActivity.this)) {
                    JumpHelper.jump(MainActivity.this, GeRenZiLiaoActivity.class, false);
                } else {//未登录
                    JumpHelper.jump(MainActivity.this, LoginActivity.class, false);
                }
                break;
            case R.id.ll_drawer_qiyeguanli://企业管理
                drawerLayout.closeDrawers();
                if (SharePrefercesUtils.getLoginStatus(MainActivity.this)) {
                    JumpHelper.jump(MainActivity.this, QiYeGuanLiActivity.class, false);
                } else {//未登录
                    JumpHelper.jump(MainActivity.this, LoginActivity.class, false);
                }
                break;
            case R.id.ll_drawer_xitongtongzhi://系统通知
                drawerLayout.closeDrawers();
                if (SharePrefercesUtils.getLoginStatus(MainActivity.this)) {
                    JumpHelper.jump(MainActivity.this, XiTongTongZhiActivity.class, false);
                } else {//未登录
                    JumpHelper.jump(MainActivity.this, LoginActivity.class, false);
                }
                break;
            case R.id.ll_drawer_xinxiaoxishezhi://新消息设置
                drawerLayout.closeDrawers();
                JumpHelper.jump(MainActivity.this, XinXiaoXiSheZhiActivity.class, false);
                break;
            case R.id.ll_drawer_qingkonghuancun://清空缓存
                drawerLayout.closeDrawers();
                cleanCache();
                break;
            case R.id.ll_drawer_guanyuyubangzhu://关于与帮助
                drawerLayout.closeDrawers();
                JumpHelper.jump(MainActivity.this, GuanYuActivity.class, false);
                break;
        }
    }

    /**
     * 清空缓存
     */
    private void cleanCache() {
        //获取缓存大小
        String cacheSize = GlideCacheUtil.getInstance().getCacheSize(MainActivity.this);
        CommonDialog commonDialog = new CommonDialog(MainActivity.this, "清空缓存", "系统缓存" + cacheSize + "，点击确认清理");
        commonDialog.show();
        commonDialog.setOnClickListener(new CommonDialog.OnClickListener() {
            @Override
            public void leftClick() {
                //取消
            }

            @Override
            public void rightClick() {
                //确认
                //清除图片所有缓存
                GlideCacheUtil.getInstance().clearImageAllCache(MainActivity.this);
            }
        });
    }

    /**
     * 地图区域范围
     */
    private void departmentscopeIndex() {
        fromNetwork.departmentscopeIndex().compose(new RxActivityHelper<DepartmentscopeIndexReturn>().ioMain(MainActivity.this, false))
                .subscribe(new MySubscribe<DepartmentscopeIndexReturn>(mContext, false) {
                    @Override
                    protected void success(DepartmentscopeIndexReturn resultBean) {
                        if (resultBean.data != null) {
                            //设置全部公共 地图区域范围
                            Session.getInstance().setDepartmentscopeIndexReturn(resultBean.data);
                        }
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage);
                    }
                });
    }

    //刷新首页数据获取
    @Subscriber(tag = "MainActivity.refreshFragment")
    private void refreshFragment(boolean flag) {
        LogUtils.e("MainActivity receive MainActivity.refreshFragment");
        initLoacation();
        departmentscopeIndex();
    }

}
